﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：关联类型表
    /// </summary>
    public class ec_CableService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_CableEntity> _cableRepository => new Repository<ec_CableEntity>();
        #endregion
        #region 获取数据

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_CableEntity> GetList(string queryJson)
        {
            try
            {

                var ProjectEntity = new ec_projectEntity();
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t2.TagNumber,t.* ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    return null;
                }
                else
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($"  FROM ec_cable_{ProjectEntity.ProjectIndex} t join ec_EngineData_{ProjectEntity.ProjectIndex} t2 on t.EngineerDataID=t2.EngineDataID ");


                    var tbName = ProjectSugar.TableName<ec_CableEntity>(queryParam["ProjectId"].ToString());

                }
                strSql.Append(" WHERE 1=1 ");


                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["EngineerDataID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("EngineerDataID", queryParam["EngineerDataID"].ToString(), DbType.String));
                    strSql.Append(" AND t2.EngineDataID = @EngineerDataID ");
                }
                //return this.BaseRepository().FindList<ec_CableEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_CableEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }



        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">cableId 或 EngineDataId</param>
        /// <summary>
        /// <returns></returns>
        public ec_CableEntity GetEntity(string ProjectId, string keyValue)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                { 
                    return _cableRepository.GetById(keyValue);
                }
                else
                { 
                    var tbName = ProjectSugar.TableName<ec_CableEntity>(ProjectId);
                    var exist = _cableRepository.AsQueryable().AS(tbName)
                        .First(x => x.EngineerDataID == keyValue || x.CableID == keyValue);

                    return exist;
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        #endregion

        #region 提交数据
        /// <summary>
        /// 删除实体数据(cable set wire)
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string ProjectId, string CableID)
        {
            //var db = this.BaseRepository().BeginTrans();
            _cableRepository.AsTenant().BeginTran();
            try
            {
                //关联类型删除时，删除工程数据关联表记录。
                if (string.IsNullOrWhiteSpace(ProjectId))
                {

                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    //db.ExecuteBySql($@" DELETE FROM ec_Cable_{ProjectEntity.ProjectIndex} WHERE CableID ='{CableID}'; ");
                    //db.ExecuteBySql($@" DELETE FROM ec_Cable_Set_{ProjectEntity.ProjectIndex} WHERE CableID ='{CableID}'; ");
                    //db.ExecuteBySql($@" DELETE FROM ec_Cable_Set_Wire_{ProjectEntity.ProjectIndex} WHERE CableID ='{CableID}'; ");
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_Cable_{ProjectEntity.ProjectIndex} WHERE CableID ='{CableID}'; ");
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_Cable_Set_{ProjectEntity.ProjectIndex} WHERE CableID ='{CableID}'; ");
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_Cable_Set_Wire_{ProjectEntity.ProjectIndex} WHERE CableID ='{CableID}'; ");
                }
                //db.Commit();
                _cableRepository.AsTenant().CommitTran();
            }
            catch (Exception ex)
            {
                _cableRepository.AsTenant().RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <param name="NewID">新ID（新建） 或者 老ID（更新）</param>
        public void SaveEntity(string ProjectId, string keyValue, ec_CableEntity entity, out String NewID)
        {
            try
            {
                NewID = "0";
                var ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }
                else
                {
                    return;
                }

                if (!string.IsNullOrEmpty(keyValue))
                {

                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Update(entity);
                        _cableRepository.Update(entity);
                    }
                    else
                    {
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_Cable_{ProjectEntity.ProjectIndex}", "CableID");
                        _cableRepository.AsUpdateable(entity).AS($"ec_Cable_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }

                    NewID = keyValue;
                }
                else
                {
                    //避免重复
                    var exist = _cableRepository.AsQueryable().AS($"ec_Cable_{ProjectEntity.ProjectIndex}").First(x => x.EngineerDataID == entity.EngineerDataID);
                    if (exist == null)
                    {
                        entity.Create();

                        //this.BaseRepository().InsertByNoMap(entity, $"ec_Cable_{ProjectEntity.ProjectIndex}");
                        _cableRepository.AsInsertable(entity).AS($"ec_Cable_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                        NewID = entity.CableID;
                    }
                    else
                    {
                        NewID = exist.CableID;
                    }

                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
